package com.jar.exercise.java8新特性.StreamAPI;


import com.jar.exercise.java8新特性.方法的引用.Employee;
import org.junit.Test;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * Steam API的中间操作
 * <p>
 * 筛选与切片
 * <p>
 * 映射
 * <p>
 * 字符串算法
 */


public class TestStreamAPI2 {
	/**
	 * 筛选与切片
	 */


	@Test
	public void test1() {

		List<Employee> student = Employee.getStudent();
		Stream<Employee> stream = student.stream();
		//查询员工种年龄大于15的员工信息
		stream.filter(e -> e.getAge() > 15).forEach(System.out::println);

		System.out.println();
		//limit()截断流
		student.stream().limit(1).forEach(System.out::println);

        System.out.println();
        student.stream().skip(1).forEach(System.out::println);

        System.out.println();
        //一定要重写 equals 和 hashcode()方法
        student.stream().distinct().forEach(System.out::println);

    }


/**
 * 映射
 */

    @Test
    public void test2() {
        //map()接受一个函数，作为一个参数，将元素转换成其他形式的结果
        //转换大小写
        List<String> list = Arrays.asList("aa", "bb", "cc", "dd");
        list.stream().map(String::toUpperCase).forEach(System.out::println);
        list.stream().map(str -> str.toUpperCase()).forEach(System.out::println);

        //获取员工姓名长度大于2的员工姓名
        List<Employee> student = Employee.getStudent();
        student.stream().map(e -> e.getName().length() > 2).forEach(System.out::println);

        student.stream().map(Employee::getName).filter(s -> s.length() > 2).forEach(System.out::println);

    }

/**
 * 字符串算法
 */

    @Test
    public void test3() {
        List<Integer> integers = Arrays.asList(12, 23, 0, -8, 65, 123);
        //sorted();
        integers.stream().sorted().forEach(System.out::println);
        //sorted(Comparator<? super T> comparator);
        List<Employee> student = Employee.getStudent();
        //抛异常，Employee没有实现Comparable类
        student.stream().sorted(Comparator.comparingInt(Employee::getAge)).forEach(System.out::println);
        //reversed()相反方向排序
        student.stream().sorted(Comparator.comparingInt(Employee::getAge).reversed()).forEach(System.out::println);

    }
    @Test
    public void test4(){
	    List<Integer> integers = Arrays.asList(12, 23, 0, -8, 65, 123);
        integers.sort(Comparator.naturalOrder()) ;
        System.out.println(integers);
    }

    @Test
    public void test5() {

        List<String> list = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd");

//        Optional<String> max = list.stream().max(Comparator.comparing(String::length));
        Optional<String> max = list.stream().max(Comparator.comparingInt(String::length));
        System.out.println("最长的字符串：" + max.get());
    }
}

